<template>
  <div class="city">
    <van-nav-bar left-arrow @click-left="onClickLeft" fixed title="城市列表" ref="city"/>
    <van-index-bar :index-list="indexList">
      <van-index-anchor v-for="(value, key) in obj" :key="key" :index="key">
        {{ key }}
        <van-cell v-for="(item, index) in value" :key="index" @click="city(item)">{{
          item
        }}</van-cell>
      </van-index-anchor>
    </van-index-bar>
  </div>
</template>

<script>
import { getCity, hotCity, searchCity } from '@/api/city'
export default {
  name: 'city-page',
  data () {
    return {
      list: [],
      hotList: [],
      indexList: [],
      obj: {},
      value: ''

    }
  },
  methods: {
    onClickLeft () {
      this.$router.back()
    },
    async city (item) {
      const res3 = await searchCity(item)
      console.log(res3)
      this.value = res3.body.value
      console.log(item)
      this.$router.push(`/home?name=${item}&value=${this.value}`)
    }
  },
  async created () {
    const hot = await hotCity()
    hot.body.forEach(item => {
      this.hotList.push(item.label)
    })
    // this.hotList = hot.body

    const res = await getCity()
    console.log(res)
    res.body.forEach((item) => {
      this.list.push(item.short.toUpperCase().substring(0, 1))
    })
    this.list.forEach((item) => {
      if (this.indexList.indexOf(item) === -1) {
        this.indexList.push(item)
      }
    })

    this.indexList = this.indexList.sort()
    this.indexList.splice(0, 0, '#', '热')
    this.indexList.forEach((item) => {
      this.obj[item] = []
      for (let i = 0; i < res.body.length; i++) {
        const res1 = res.body[i].pinyin[0].toUpperCase()
        if (item === res1) {
          this.obj[item].push(res.body[i].label)
        }
      }
    })
    this.obj.热 = this.hotList
    for (const k in this.obj) {
      if (this.obj[k].length === 0) {
        this.obj[k].push(this.$route.params.currentCity)
      }
    }
    console.log(this.obj)
  }
}
</script>

<style lang="less" scoped>
.city {
  margin-top: 50px;
}
</style>
